//
//  MAlertView.m
//  IpadVideo
//
//  Created by 红沙尘 on 14-7-1.
//  Copyright (c) 2014年 红沙尘. All rights reserved.
//

#import "MAlertView.h"
#import "MTool.h"

@implementation MAlertView
@synthesize delegate;


- (void)awakeFromNib
{
    [super awakeFromNib];
    
//    self.layer.cornerRadius = 1.0f;
//    self.layer.masksToBounds = YES;
//    self.layer.borderColor = ARGB(220, 220, 220, 1).CGColor;
//    self.layer.borderWidth = 1.0f/[UIScreen mainScreen].scale;
    
    label.font = [UIFont systemFontOfSize:16.0f];
}

- (void)showWithTitle:(NSString *)title
               inView:(UIView *)view
             complete:(void(^)(void))complete {
    
    [self showWithTitle:title inView:view];
    
    [self performSelector:@selector(removeWithcomplete:) withObject:complete afterDelay:1.5];
}

- (void)showWithTitle:(NSString *)title inView:(UIView *)view
{
    [view addSubview:self];
    
    label.text = title;
    
    CGFloat width = ScreenWidth - 40;
    
    CGSize size = [MTool sizeWithText:label.text
                                 font:label.font
                    constrainedToSize:CGSizeMake(width, 500)];
    
    CGRect frame = self.frame;
    frame.size.height = MAX(size.height + 30, 53);
    frame.size.width  = size.width + 80;
    frame.origin.y = (view.frame.size.height-frame.size.height)/2;
    frame.origin.x = (view.frame.size.width-frame.size.width)/2;
    self.frame = frame;
    
    CGRect lFrame = label.frame;
    lFrame.size.height = frame.size.height;
    lFrame.size.width  = frame.size.width;
    label.frame = lFrame;
    
    UIImage *alert_bg = LoadImage(@"alert_bg");
    UIImageView *bg = [[UIImageView alloc] initWithFrame:self.bounds];
    bg.image = [alert_bg stretchableImageWithLeftCapWidth:alert_bg.size.width/2
                                             topCapHeight:alert_bg.size.height/2];
    [self insertSubview:bg atIndex:0];
    
    [self performSelector:@selector(remove) withObject:nil afterDelay:3.0];
}

- (void)remove
{
    [UIView animateWithDuration:0.3 animations:^{
        self.alpha = 0;
    }completion:^(BOOL finished){
        
        if ([delegate respondsToSelector:@selector(malertviewDidMiss)])
        {
            [delegate malertviewDidMiss];
        }
        
        [self removeFromSuperview];
    }];
}

- (void)removeWithcomplete:(void(^)(void))complete {
    
    [UIView animateWithDuration:0.3 animations:^{
        self.alpha = 0;
    } completion:^(BOOL finished){
        
        complete();
        
        [self removeFromSuperview];
    }];
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end
